﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace update
{
    public partial class Form1 : Form
    {
        List<DownloadFile> fileList;
        String currentDirectory = System.Environment.CurrentDirectory + "\\";
        Stopwatch stopWatch;
        string checkExePath = ConfigurationManager.AppSettings["checkExePath"];
        string downloadFileListUrl = ConfigurationManager.AppSettings["downloadFileListUrl"];
        string processesName = ConfigurationManager.AppSettings["processesName"];
        string basePath = ConfigurationManager.AppSettings["basePath"];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        Boolean exception = false;

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            textBox1.Text += (string)e.UserState;
            if (textBox1.Text.Contains("失败"))
                exception = true;

            progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            textBox1.Text += "处理完成\r\n";

            stopWatch.Stop();
            TimeSpan timespan = stopWatch.Elapsed; //  获取当前实例测量得出的总时间
            double hours = timespan.TotalHours; // 总小时
            double minutes = timespan.TotalMinutes;  // 总分钟
            double seconds = timespan.TotalSeconds;  //  总秒数
            double milliseconds = timespan.TotalMilliseconds;  //  总毫秒数

            textBox1.Text += "运行耗时: " + timespan.TotalSeconds + " 秒\r\n\r\n";

            if(!exception && !checkExePath.Equals(""))
                Process.Start(checkExePath);

        }

        string getFileVersion(string filePath)
        {
            string FileVersions = "";

            try
            {
                System.Diagnostics.FileVersionInfo file1 = System.Diagnostics.FileVersionInfo.GetVersionInfo(filePath);
                FileVersions = file1.FileVersion;
                if (FileVersions != "")
                {
                    string[] strVer = FileVersions.Split('.');
                    if (strVer.Length == 2)
                    {
                        FileVersions = strVer[0] + ".00.0000";
                    }

                }
            }
            catch (Exception)
            {
                FileVersions = "";
            }
            return FileVersions;
        }

        void httpDownloadFile(string url, string path)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();

            String dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            //创建本地文件写入流
            Stream stream = new FileStream(path, FileMode.Create);

            byte[] bArr = new byte[1024 * 1024 * 32];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }

            stream.Close();
            responseStream.Close();
        }

        String httpDownloadFile4IndexDotJson(string url)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();

            byte[] bArr = new byte[1024 * 1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            string content = Encoding.Default.GetString(bArr, 0, size);
            while (size > 0)
            {
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
                if(size > 0)
                    content += Encoding.Default.GetString(bArr, 0, size);
            }

            responseStream.Close();
            
            return content;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var bgworker = sender as BackgroundWorker;

            int index = 0;
            Boolean notFinish = false;

            foreach(DownloadFile downloadFile in this.fileList)
            {
                bgworker.ReportProgress(index, "准备下载, " + downloadFile.halfFullPath + "文件大小: " + downloadFile.fileSize + "\r\n");

                if(justMain)
                {
                    String test = checkExePath.Substring(checkExePath.LastIndexOf("\\") + 1);
                    if (!downloadFile.downloadPath.Contains(test))
                    {
                        bgworker.ReportProgress(index, "跳过\r\n");
                        continue;
                    }
                }

                try
                {
                    httpDownloadFile(downloadFile.downloadPath, currentDirectory + downloadFile.halfFullPath);

                }catch(Exception error)
                {
                    notFinish = true;
                    bgworker.ReportProgress(100, "下载异常: " + error.Message + "\r\n\r\n");
                    continue;
                }

                index += 100 / this.fileList.Count;
                bgworker.ReportProgress(index, "下载完成\r\n\r\n");
            }

            if (!notFinish)
            {
                bgworker.ReportProgress(99, "\r\n全部下载完成！\r\n");
                bgworker.ReportProgress(100, "文件保存在：" + currentDirectory + "\r\n");
            } else
                bgworker.ReportProgress(100, "\r\n只下载了部分文件，请检查\r\n");


        }

        void kill(String processesName)
        {
            foreach (Process p in Process.GetProcessesByName(processesName))
            {
                textBox1.Text += "查询到指定进程\r\n";
                p.Kill();
                textBox1.Text += "终止进程成功\r\n";
            }
        }

        private void 关于ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("睿依科技，c端软件更新工具。vx：18610348075");
        }

        private void 生成indexjsonToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            if (!folderBrowserDialog1.SelectedPath.Equals(""))
            {
                traversalDir(folderBrowserDialog1.SelectedPath);
                DownloadFileListVo test = new DownloadFileListVo();
                test.currentVersion = "1.0.8";
                test.fileList = list4OutputIndexFile;

                String json2 = JsonConvert.SerializeObject(test);
                File.WriteAllText(currentDirectory + @"\index.json", json2);

                textBox1.Text = "下载索引文件保存在：" + currentDirectory + @"\index.json";
            }

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox1.SelectionStart = textBox1.Text.Length;
            textBox1.ScrollToCaret();
        }

        List<DownloadFile> list4OutputIndexFile = new List<DownloadFile>();

        void traversalDir(string dir)
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            FileSystemInfo[] fsinfos = null;
            try
            {
                fsinfos = d.GetFileSystemInfos();

            } catch(Exception error)
            {
                Console.WriteLine(error.Message);
            }

            if (fsinfos == null)
                return;

            foreach (FileSystemInfo fsinfo in fsinfos)
            {
                try
                {
                    if (fsinfo is DirectoryInfo)
                        traversalDir(fsinfo.FullName);
                    else
                    {
                        Console.WriteLine(fsinfo.FullName);//输出文件的全部路径
                        FileInfo fileInfo = new FileInfo(fsinfo.FullName);

                        DownloadFile downloadFile = new DownloadFile();
                        downloadFile.downloadPath = basePath + "/" + Path.GetFileName(fsinfo.FullName);
                        downloadFile.halfFullPath = Path.GetFileName(fsinfo.FullName);
                        downloadFile.fileSize = Math.Ceiling(fileInfo.Length / (1024.0 * 1024.0)) + " mb";

                        list4OutputIndexFile.Add(downloadFile);
                    }
                }
                catch (Exception error)
                {
                    Console.WriteLine(error.Message);
                }
            }
        }

        Boolean justMain = false;

        void startUpdate()
        {
            textBox1.Text = "下载索引文件: " + downloadFileListUrl + "\r\n\r\n";
            string json;
            try
            {
                json = httpDownloadFile4IndexDotJson(downloadFileListUrl);
            } catch(Exception error)
            {
                textBox1.Text += "异常: " + error.Message;
                return;
            }

            Console.WriteLine(json);

            DownloadFileListVo downloadFileListVo = JsonConvert.DeserializeObject<DownloadFileListVo>(json);
            if (downloadFileListVo != null)
            {
                //String localVersion = getFileVersion(checkExePath);

                //textBox1.Text += "远程服务器中，文件版本: " + downloadFileListVo.currentVersion + "\r\n";
                //textBox1.Text += "本地文件版本: " + localVersion + "\r\n\r\n";

                //Version v1 = new Version(downloadFileListVo.currentVersion);
                //Version v2 = new Version(localVersion);

                //if (v1.CompareTo(v2) > 0)
                if (true)
                {
                    textBox1.Text += "开始更新\r\n\r\n";

                    kill(processesName);

                    fileList = downloadFileListVo.fileList;

                    stopWatch = new Stopwatch();
                    stopWatch.Start();
                    backgroundWorker1.RunWorkerAsync();
                }
                else
                    textBox1.Text += "本地文件已经是最新版本\r\n\r\n";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            justMain = false;
            startUpdate();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            justMain = true;
            startUpdate();
        }
    }
}
